package com.example.jl.bethinner.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.jl.bethinner.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by JL on 9/7/15.
 */


public class ACView extends View {

    private float mBorderWidth;//线的宽度

    private ImageView imageView;

    private int mBorderColor;
    private int rulerColor = 0x7DC0C0C0;
    private Bitmap bitmapBackground;//背景图
    private Bitmap bitmapCursor;//游标图
    private Bitmap bitmapOpen;//打开按钮图
    private Bitmap bitmapColse;//关闭按钮图

    private Paint mPaint;
    private Paint rulerPaint;
    /**
     * 圆环半径 Note: (Re)在onMeasure计算{@link #onMeasure(int, int)}
     */
    private RectF mBounds;
    private float width;
    private float height;
    float mRadians = 0f;//默认弧度
    private float timeRotate = calculateAngleFromRadians(mRadians);
    ;//默认角度
    private float circleRotate = 40;//小圆半径
    float radius;
    float smallLength;
    float largeLength;
    float downX;
    float downY;
    float moveX;
    float moveY;
    private int MODEL = 0;//默认第一种模式，总共应该目前是有4种，/0送风,1制冷,2制热,3除湿
    private List<String> models;
    private int MaxValue = 30;//设置的最大值得最小值
    private int MinValue = 16;
    private int gray_line_number = MaxValue - MinValue;//灰条纹个数
    private int MaxAngle = 210;//最大角度
    private float[] pointerPosition;//外部圆圆心
    // 添加游标上的文字
    private Paint cursorPaint;
    private Paint centerMathPaint;//中心数字画笔
    private Paint centerStringPaint;//中心文字画笔

    private Boolean isOpen = false; //开关状态
    private Boolean isControlSwitch = false;//手指是否是去控制开关的


    public ACView(Context context) {
        super(context);
        init();
    }

    public ACView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.getTheme()
                .obtainStyledAttributes(
                        attrs,
                        R.styleable.CustomView
                        , 0, 0);

        try {
            mBorderColor = typedArray.getColor(R.styleable.CustomView_border_color, 0xff000000);
            mBorderWidth = typedArray.getDimension(R.styleable.CustomView_border_width, 2);
        } finally {
            typedArray.recycle();
        }

        init();
    }

    public ACView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        models = new ArrayList<>();
        models.add("送风");
        models.add("制冷");
        models.add("制热");
        models.add("除湿");
        initPaint();
        initBitmap();


    }

    private void initPaint() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mBorderWidth);
        mPaint.setColor(mBorderColor);

        //刻度画笔
        rulerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        rulerPaint.setStyle(Paint.Style.STROKE);
        rulerPaint.setStrokeWidth(mBorderWidth);
        rulerPaint.setColor(rulerColor);

        cursorPaint = new Paint();
        cursorPaint.setColor(Color.GRAY);
        cursorPaint.setTextSize((int) (45 * 1));
        cursorPaint.setAntiAlias(true);
        cursorPaint.setTextAlign(Paint.Align.CENTER);


        centerMathPaint = new Paint();
        centerMathPaint.setColor(0XFF2C83EF);
        centerMathPaint.setTextSize((int) (90 * 1));
        centerMathPaint.setAntiAlias(true);
        centerMathPaint.setTextAlign(Paint.Align.CENTER);

        centerStringPaint = new Paint();
        centerStringPaint.setColor(0XFF2C83EF);
        centerStringPaint.setTextSize((int) (30 * 1));
        centerStringPaint.setAntiAlias(true);
        centerStringPaint.setTextAlign(Paint.Align.CENTER);
    }

    private void initBitmap() {
        bitmapBackground = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ac_view_background);
        bitmapCursor = BitmapFactory.decodeResource(getResources(),
                R.mipmap.cursor_icon);
        bitmapOpen = BitmapFactory.decodeResource(getResources(),
                R.mipmap.open_control_icon);
        bitmapColse = BitmapFactory.decodeResource(getResources(),
                R.mipmap.close_control_icon);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mBounds = new RectF(getLeft(), getTop(), getRight(), getBottom());

        width = mBounds.right - mBounds.left;
        height = mBounds.bottom - mBounds.top;

        if (width < height) {
            radius = width * 7 / 18;
        } else {
            radius = height * 7 / 18;
        }

        smallLength = 10;
        largeLength = 20;
        pointerPosition = calculatePointerPosition(mRadians);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawBitmap(bitmapBackground, null, new RectF(mBounds.centerX() - radius, mBounds.centerY() - radius, mBounds.centerX() + radius, mBounds.centerY() + radius), null);
        if (isOpen) {
            canvas.drawBitmap(bitmapOpen, null, new RectF(mBounds.centerX() - radius / 8, mBounds.centerY() - radius / 8 * 5, mBounds.centerX() + radius / 8, mBounds.centerY() - radius / 8 * 3), null);
        } else {
            canvas.drawBitmap(bitmapColse, null, new RectF(mBounds.centerX() - radius / 8, mBounds.centerY() - radius / 8 * 5, mBounds.centerX() + radius / 8, mBounds.centerY() - radius / 8 * 3), null);
        }
        canvas.save();
        int showValue = (int) (MinValue + (timeRotate / MaxAngle) * (MaxValue - MinValue));
        //中间的数字
        canvas.drawText(showValue + "°", (mBounds.centerX()), (mBounds.centerY()),
                centerMathPaint);
        //中间的文字
        canvas.drawText(models.get(MODEL), (mBounds.centerX()), (mBounds.centerY()),
                centerStringPaint);




        mPaint.setColor(mBorderColor);

//        canvas.drawCircle(mBounds.centerX(), mBounds.centerY(), radius, mPaint);//外圆

//        canvas.drawCircle(mBounds.centerX(), mBounds.centerY(), circleRotate, mPaint);//中心圆
        //画 最小值，中间值，最大值
        setCursorValue(canvas, MinValue, 0);
        setCursorValue(canvas, (MinValue + MaxValue) / 2, MaxAngle / 2);
        setCursorValue(canvas, MaxValue, MaxAngle);


        //  添加游标 游标为圆形
        canvas.drawCircle(mBounds.centerX() + pointerPosition[0], mBounds.centerY() + pointerPosition[1], radius / 5, mPaint);//外部游标圆
        //  添加游标资源图

        float cursorHalf = (float) (radius / 5);
        Matrix matrix = new Matrix();
        matrix.postRotate(timeRotate, mBounds.centerX(), mBounds.centerY());
        canvas.concat(matrix);
        canvas.drawBitmap(bitmapCursor, null, new RectF(mBounds.centerX() - cursorHalf, mBounds.centerY() - radius * 9 / 8 - cursorHalf, mBounds.centerX() + cursorHalf, mBounds.centerY() - radius * 9 / 8 + cursorHalf), null);

        canvas.drawText(showValue + "°", mBounds.centerX(), (mBounds.centerY() - radius * 9 / 8),
                cursorPaint);
        canvas.restore();

    }

    public void setCursorValue(Canvas canvas, int value, int rotate) {
        canvas.drawText(value + "°", mBounds.centerX() + radius * 7 / 8 * (float) Math.sin(Math.toRadians(rotate)),
                (mBounds.centerY() - radius * 7 / 8 * (float) Math.cos(Math.toRadians(rotate))),
                cursorPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {


        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                downX = event.getX();
                downY = event.getY();
                //判断开关的按钮大小
                if (downX > mBounds.centerX() - radius / 4 && downY > mBounds.centerY() - radius / 8 * 6
                        && downX < mBounds.centerX() + radius / 4 && downY < mBounds.centerY() - radius / 8 * 3) {
                    isControlSwitch = true;
                    isOpen = !isOpen;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                moveX = event.getX();
                moveY = event.getY();
                if (!isControlSwitch) {
                    //计算手指和圆心的与水平方向的弧度
                    mRadians = (float) Math.atan2(moveY - mBounds.centerY(), moveX - mBounds.centerX());
                    timeRotate = calculateAngleFromRadians(mRadians);
                    if (timeRotate < MaxAngle) {
                        pointerPosition = calculatePointerPosition(mRadians);
                    } else {
                        timeRotate = MaxAngle;
                    }

                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                //在这里还原一些指定ACTION_DOWN里面改变的值
                isControlSwitch = false;
                break;
        }
        return true;
    }

    private float[] calculatePointerPosition(float radians) {
        // if (calculateRadiansFromAngle(angle) > end_wheel)
        // angle = calculateAngleFromRadians(end_wheel);
        float x = (float) ((radius) * Math.cos(radians));
        float y = (float) ((radius) * Math.sin(radians));

        return new float[]{x, y};
    }

    //通过弧度计算角度
    private int calculateAngleFromRadians(float radians) {
        float unit = (float) (radians / (2 * Math.PI));
        if (unit < 0) {
            unit += 1;
        }
        int angle = (int) ((unit * 360) - ((360 / 4) * 3));
        if (angle < 0)
            angle += 360;
        return angle;
    }

    //通过角度计算弧度
    private float calculateRadiansFromAngle(float angle) {
        return (float) (((angle + 270) * (2 * Math.PI)) / 360);
    }

}
